<template>
  <div class="page">
    <h2>处方审核</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按病人姓名/处方号/医生搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterDept" placeholder="全部科室" style="width:160px">
        <el-option label="全部科室" :value="''" />
        <el-option v-for="d in depts" :key="d" :label="d" :value="d" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="全部状态" style="width:140px">
        <el-option label="全部状态" :value="''" />
        <el-option label="待审核" value="pending" />
        <el-option label="已通过" value="approved" />
        <el-option label="已驳回" value="rejected" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="refresh">刷新</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <div class="muted">提示：此页面为前端静态演示，数据为示例假数据，用于演示处方审核流程与用药警示。</div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prescNo" label="处方号" min-width="140" />
      <el-table-column prop="patientName" label="病人" width="160" />
      <el-table-column prop="patientId" label="病人ID" width="120" />
      <el-table-column prop="doctor" label="开方医生" width="140" />
      <el-table-column prop="dept" label="科室" width="120" />
      <el-table-column prop="drugCount" label="药品数" width="100" />
      <el-table-column prop="createdAt" label="提交时间" width="160" />
      <el-table-column prop="status" label="审核状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='approved' ? 'success' : (row.status==='rejected' ? 'danger' : 'warning')">
            {{ row.status==='approved' ? '已通过' : (row.status==='rejected' ? '已驳回' : '待审核') }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="190">
        <template #default="{ row }">
          <el-button size="small" @click="openDetail(row.id)">查看</el-button>
          <el-button size="small" type="success" @click="approveOne(row.id)" style="margin-left:8px">通过</el-button>
          <el-button size="small" type="danger" @click="rejectOne(row.id)" style="margin-left:8px">驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchApprove">批量通过</el-button>
      <el-button @click="batchReject">批量驳回</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <!-- detail dialog -->
    <el-dialog title="处方详情" v-model="showDetail" width="720px">
      <div v-if="detail" style="max-height:60vh;overflow:auto">
        <div style="display:flex;gap:24px;margin-bottom:12px">
          <div><strong>处方号：</strong> {{ detail.prescNo }}</div>
          <div><strong>提交时间：</strong> {{ detail.createdAt }}</div>
        </div>
        <div style="display:flex;gap:24px;margin-bottom:12px">
          <div><strong>病人：</strong> {{ detail.patientName }}（{{ detail.patientId }}）</div>
          <div><strong>年龄/性别：</strong> {{ detail.age }} / {{ detail.gender }}</div>
          <div><strong>科室：</strong> {{ detail.dept }}</div>
        </div>

        <el-table :data="detail.drugs" border style="width:100%">
          <el-table-column prop="name" label="药品" width="220" />
          <el-table-column prop="dose" label="剂量/频次" width="160" />
          <el-table-column prop="route" label="给药途径" width="120" />
          <el-table-column prop="qty" label="数量" width="80" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="用药警示" width="200">
            <template #default="{ row }">
              <div v-if="row.alerts && row.alerts.length">
                <el-tag v-for="a in row.alerts" :key="a" type="danger" style="margin-right:6px">{{ a }}</el-tag>
              </div>
              <div v-else class="muted">无</div>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top:12px">
          <strong>医生备注：</strong> {{ detail.note || '无' }}
        </div>
      </div>

      <template #footer>
        <el-button @click="closeDetail">关闭</el-button>
        <el-button type="success" @click="approveFromDetail">通过</el-button>
        <el-button type="danger" @click="rejectFromDetail">驳回</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_PRESCRIPTIONS = [
  { id: 1, prescNo: 'P20251001-001', patientName: '张三', patientId: 'Z1001', age: 45, gender: '男', doctor: '李医生', dept: '精神科', drugCount: 2, createdAt: '2025-10-20 09:12', status: 'pending', note: '注意过敏史', drugs: [ { name: '氟西汀', dose: '20mg qd', route: '口服', qty: 30, remark: '', alerts: ['与MAOI同用风险'] }, { name: '阿普唑仑', dose: '0.25mg hs', route: '口服', qty: 10, remark: '睡前使用', alerts: ['与酒精相互作用'] } ] },
  { id: 2, prescNo: 'P20251002-002', patientName: '李四', patientId: 'L2002', age: 60, gender: '女', doctor: '王医生', dept: '内科', drugCount: 1, createdAt: '2025-10-21 14:05', status: 'approved', note: '', drugs: [ { name: '阿司匹林', dose: '100mg qd', route: '口服', qty: 30, remark: '', alerts: ['出血风险'] } ] },
  { id: 3, prescNo: 'P20251003-003', patientName: '王五', patientId: 'W3003', age: 30, gender: '男', doctor: '赵医生', dept: '精神科', drugCount: 3, createdAt: '2025-10-22 11:30', status: 'pending', note: '有肝功能偏高', drugs: [ { name: '奎硫平', dose: '300mg qd', route: '口服', qty: 30, remark: '', alerts: ['代谢受肝功能影响'] }, { name: '拉莫三嗪', dose: '100mg bid', route: '口服', qty: 60, remark: '', alerts: [] }, { name: '安定', dose: '10mg prn', route: '口服', qty: 10, remark: '短期使用', alerts: ['镇静作用'] } ] },
  { id: 4, prescNo: 'P20251004-004', patientName: '赵六', patientId: 'Z4004', age: 70, gender: '女', doctor: '刘医生', dept: '老年科', drugCount: 2, createdAt: '2025-10-23 08:20', status: 'rejected', note: '剂量超出推荐', drugs: [ { name: '苯二氮卓类', dose: '2mg qd', route: '口服', qty: 60, remark: '', alerts: ['老年人跌倒风险'] }, { name: '地塞米松', dose: '5mg qd', route: '口服', qty: 20, remark: '', alerts: ['长期使用需监测血糖'] } ] },

  { id: 5, prescNo: 'P20251005-005', patientName: '孙七', patientId: 'S5005', age: 28, gender: '女', doctor: '高医生', dept: '妇产科', drugCount: 1, createdAt: '2025-10-23 10:45', status: 'pending', note: '', drugs: [ { name: '甲硝唑', dose: '400mg tid', route: '口服', qty: 21, remark: '', alerts: ['与酒精禁忌'] } ] },
  { id: 6, prescNo: 'P20251006-006', patientName: '周八', patientId: 'Z6006', age: 4, gender: '男', doctor: '程医生', dept: '儿科', drugCount: 2, createdAt: '2025-10-24 09:00', status: 'approved', note: '', drugs: [ { name: '青霉素', dose: '按体重', route: '注射', qty: 1, remark: '肌注', alerts: ['过敏史注意'] }, { name: '退热贴', dose: '外用', route: '外用', qty: 5, remark: '', alerts: [] } ] },
  { id: 7, prescNo: 'P20251007-007', patientName: '吴九', patientId: 'W7007', age: 52, gender: '男', doctor: '孙医生', dept: '心内科', drugCount: 2, createdAt: '2025-10-24 11:20', status: 'pending', note: '有既往心梗史', drugs: [ { name: '阿托伐他汀', dose: '20mg qd', route: '口服', qty: 30, remark: '', alerts: ['与某些抗生素相互作用'] }, { name: '氯吡格雷', dose: '75mg qd', route: '口服', qty: 30, remark: '', alerts: ['出血风险'] } ] },
  { id: 8, prescNo: 'P20251008-008', patientName: '郑十', patientId: 'Z8008', age: 38, gender: '女', doctor: '何医生', dept: '皮肤科', drugCount: 1, createdAt: '2025-10-25 13:45', status: 'approved', note: '', drugs: [ { name: '他克莫司软膏', dose: '外用', route: '外用', qty: 1, remark: '薄涂', alerts: [] } ] },

  { id: 9, prescNo: 'P20251009-009', patientName: '陈十一', patientId: 'C9009', age: 66, gender: '女', doctor: '冯医生', dept: '感染科', drugCount: 2, createdAt: '2025-10-25 15:00', status: 'pending', note: '肾功能中度受损', drugs: [ { name: '左氧氟沙星', dose: '500mg qd', route: '口服', qty: 10, remark: '', alerts: ['肾功能调整剂量'] }, { name: '洛伐他汀', dose: '20mg qd', route: '口服', qty: 30, remark: '', alerts: ['与部分抗生素相互作用'] } ] },
  { id: 10, prescNo: 'P20251010-010', patientName: '蒋十二', patientId: 'J10010', age: 49, gender: '男', doctor: '裴医生', dept: '呼吸科', drugCount: 1, createdAt: '2025-10-26 08:10', status: 'rejected', note: '需影像学结果后复诊', drugs: [ { name: '沙丁胺醇吸入', dose: '必要时', route: '吸入', qty: 1, remark: '', alerts: [] } ] },
  { id: 11, prescNo: 'P20251011-011', patientName: '胡十三', patientId: 'H11011', age: 55, gender: '男', doctor: '韩医生', dept: '肿瘤科', drugCount: 3, createdAt: '2025-10-26 10:30', status: 'pending', note: '化疗期间', drugs: [ { name: '奥沙利铂', dose: '按方案', route: '静脉输注', qty: 1, remark: '', alerts: ['神经毒性'] }, { name: '氟尿嘧啶', dose: '按方案', route: '静脉输注', qty: 1, remark: '', alerts: ['胃肠道反应'] }, { name: '止吐药', dose: '必要时', route: '口服', qty: 10, remark: '', alerts: [] } ] },

  { id: 12, prescNo: 'P20251012-012', patientName: '方十四', patientId: 'F12012', age: 34, gender: '女', doctor: '纪医生', dept: '精神科', drugCount: 2, createdAt: '2025-10-27 09:50', status: 'approved', note: '', drugs: [ { name: '舍曲林', dose: '50mg qd', route: '口服', qty: 30, remark: '', alerts: ['性功能副作用'] }, { name: '盐酸二甲双胍', dose: '500mg bid', route: '口服', qty: 60, remark: '患者合并糖尿病', alerts: ['监测肾功能'] } ] },
  { id: 13, prescNo: 'P20251013-013', patientName: '柯十五', patientId: 'K13013', age: 23, gender: '男', doctor: '彭医生', dept: '急诊科', drugCount: 1, createdAt: '2025-10-27 12:15', status: 'pending', note: '', drugs: [ { name: '止痛片', dose: '必要时', route: '口服', qty: 8, remark: '', alerts: [] } ] },
  { id: 14, prescNo: 'P20251014-014', patientName: '袁十六', patientId: 'Y14014', age: 81, gender: '女', doctor: '蒋医生', dept: '老年科', drugCount: 2, createdAt: '2025-10-28 08:40', status: 'pending', note: '多药联用，注意药物相互作用', drugs: [ { name: '华法林', dose: '按INR调整', route: '口服', qty: 30, remark: '', alerts: ['出血风险，与多药物交互'] }, { name: '氢氯噻嗪', dose: '12.5mg qd', route: '口服', qty: 30, remark: '', alerts: ['影响电解质'] } ] },
  { id: 15, prescNo: 'P20251015-015', patientName: '殷十七', patientId: 'Y15015', age: 47, gender: '男', doctor: '倪医生', dept: '内科', drugCount: 1, createdAt: '2025-10-28 10:00', status: 'approved', note: '', drugs: [ { name: '二甲双胍', dose: '500mg bid', route: '口服', qty: 60, remark: '', alerts: ['肾功能不全慎用'] } ] }
];

const prescriptions = ref([]);
const q = ref('');
const filterDept = ref('');
const filterStatus = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showDetail = ref(false);
const detail = ref(null);

onMounted(()=>{ load(); });
function load(){ prescriptions.value = JSON.parse(JSON.stringify(DEFAULT_PRESCRIPTIONS)); }

const depts = computed(()=>{ const s=new Set(prescriptions.value.map(p=>p.dept)); return Array.from(s); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return prescriptions.value.filter(p=>{
    if(qq && !(String(p.prescNo).toLowerCase().includes(qq) || p.patientName.toLowerCase().includes(qq) || p.doctor.toLowerCase().includes(qq))) return false;
    if(filterDept.value && p.dept !== filterDept.value) return false;
    if(filterStatus.value && p.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openDetail(id){ const it = prescriptions.value.find(p=>p.id===id); if(it){ detail.value = JSON.parse(JSON.stringify(it)); showDetail.value = true; } }
function closeDetail(){ showDetail.value = false; detail.value = null; }

function approveOne(id){ const it = prescriptions.value.find(p=>p.id===id); if(!it) return; ElMessageBox.confirm('确认通过该处方？','审核确认',{ confirmButtonText:'通过', cancelButtonText:'取消', type:'info' })
  .then(()=>{ it.status = 'approved'; ElMessage.success('已通过'); })
  .catch(()=>{});
}
function rejectOne(id){ const it = prescriptions.value.find(p=>p.id===id); if(!it) return; ElMessageBox.prompt('请输入驳回原因','驳回处方',{ confirmButtonText:'确定', cancelButtonText:'取消', inputPattern: /\S+/, inputErrorMessage: '需要填写驳回原因' })
  .then(({ value })=>{ it.status = 'rejected'; it.note = (it.note? it.note + ' | ' : '') + '驳回原因：' + value; ElMessage.success('已驳回'); })
  .catch(()=>{});
}

function approveFromDetail(){ if(!detail.value) return; const it = prescriptions.value.find(p=>p.id===detail.value.id); if(it){ it.status='approved'; ElMessage.success('已通过'); closeDetail(); } }
function rejectFromDetail(){ if(!detail.value) return; const it = prescriptions.value.find(p=>p.id===detail.value.id); if(!it) return; ElMessageBox.prompt('请输入驳回原因','驳回处方',{ confirmButtonText:'确定', cancelButtonText:'取消', inputPattern: /\S+/, inputErrorMessage: '需要填写驳回原因' })
  .then(({ value })=>{ it.status='rejected'; it.note = (it.note? it.note + ' | ' : '') + '驳回原因：' + value; ElMessage.success('已驳回'); closeDetail(); })
  .catch(()=>{});
}

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchApprove(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认通过 ${ids.length} 项？`,'批量操作',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'info' })
  .then(()=>{ prescriptions.value.forEach(p=>{ if(ids.includes(p.id)) p.status='approved'; }); ElMessage.success('操作完成'); selectedIds.value=[]; selectedRows.value=[]; })
  .catch(()=>{});
}
function batchReject(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.prompt('请输入批量驳回原因','批量驳回',{ confirmButtonText:'确定', cancelButtonText:'取消', inputPattern: /\S+/, inputErrorMessage: '需要填写驳回原因' })
  .then(({ value })=>{ prescriptions.value.forEach(p=>{ if(ids.includes(p.id)) { p.status='rejected'; p.note = (p.note? p.note + ' | ' : '') + '驳回原因：' + value; } }); ElMessage.success('操作完成'); selectedIds.value=[]; selectedRows.value=[]; })
  .catch(()=>{});
}
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条处方？`,'删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ prescriptions.value = prescriptions.value.filter(p=>!ids.includes(p.id)); ElMessage.success('已删除'); selectedIds.value=[]; selectedRows.value=[]; })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','prescNo','patientName','patientId','doctor','dept','drugCount','createdAt','status','note'], ...prescriptions.value.map(p=>[p.id,p.prescNo,p.patientName,p.patientId,p.doctor,p.dept,p.drugCount,p.createdAt,p.status,p.note||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href=url; a.download='prescriptions.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function refresh(){ load(); ElMessage.success('已刷新'); }
function onClear(){ /* 搜索清除 */ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>